const _ = require('lodash');

//可以编辑的键
const editKey = ['userAgreement', 'allowRegister', 'screenshotToken'];

const prefix = '/api/config';
module.exports = app => {
    const {router, middleware} = app;

    /**读取配置*/
    router.get(prefix, middleware.api(2), async ctx => {
        let message = await app.model.Message.findByPk(1);
        let config = await ctx.app.model.Config.get(editKey, {});
        config.newUserMessageTitle = message.title;
        config.newUserMessageContent = message.content;
        ctx.body = config;
    });

    /**保存配置*/
    router.post(prefix, middleware.api(2), async ctx => {
        let data = ctx.request.body;
        app.model.Message.update({
            title: data.newUserMessageTitle,
            content: data.newUserMessageContent
        }, {where: {id: 1}});
        delete data['newUserMessageTitle'];
        delete data['newUserMessageContent'];
        let values = [];
        _.each(data, (value, key) => {
            values.push({key, value});
        });
        await ctx.app.model.Config.bulkCreate(values, {updateOnDuplicate: ['value']});
        ctx.body = 'ok';
    });
};